<template>
  <div class="upload">
    <el-upload :disabled="disabled" v-bind="upload" class="avatar-uploader" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
      <img v-if="avatar" :src="avatar" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { upload, getObjectUrl } from '@/utils/cosUpload'
import { ucApi } from '@/api/api'

export default {
  data() {
    return {
      avatar: '',
      disabled: false,
      upload: {
        action: process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test' ? 'YlHomeAdmin/Dev/temp/' : 'YlHomeAdmin/temp/',
        showFileList: false,
        data: {},
        httpRequest: upload,
        multiple: false,
        ref: 'upload'
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  async created() {
    this.avatar = this.userInfo.iconUrl ? await getObjectUrl({}, [this.userInfo.iconUrl]) : require('@/assets/avatar.png')
  },
  methods: {
    // 上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async handleAvatarSuccess(res) {
      this.disabled = true
      const tempIcon = res.key
      try {
        const res = await this.$request(ucApi.updateAccountIcon, { tempIcon })
        this.avatar = await getObjectUrl({}, [res.data])
        this.$message({
          message: '上传成功',
          type: 'success'
        })
        this.$store.dispatch('user/getInfo')
        this.disabled = false
      } catch (error) {
        console.log('error', error)
        this.disabled = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
::v-deep.avatar {
  width: 100%;
  height: 100%;
  display: block;
}
</style>
